package com.cdu.service.Impl;

import com.cdu.commons.PageR;
import com.cdu.commons.ServiceCode;
import com.cdu.commons.ServiceException;
import com.cdu.mapper.CartMapper;
import com.cdu.pojo.dto.CartPageQueryDTO;
import com.cdu.pojo.dto.TokenUser;
import com.cdu.pojo.entity.Cart;
import com.cdu.pojo.vo.CartVO;
import com.cdu.service.CartService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Override
    public void addCart(Integer productId, Integer price, TokenUser tokenUser) {

        //封装数据
        //调用mapper
        //返回结果
//      //根据productId和userId查查寻商品信息
//      cartMapper.selectByProductId(productId);
        Integer userId= tokenUser.getId();
        Cart cart=cartMapper.getByUserIdAndProductId(userId,productId);
        if(cart==null){
            cart = new Cart();
            cart.setProductId(productId);
            cart.setUserId(tokenUser.getId());
            cart.setNum(1);
            cart.setPrice(price);
            cart.setCreatedUser(tokenUser.getUsername());

            //调用mapper
            int result = cartMapper.addCart(cart);
            if (result != 1) {
                throw new ServiceException("数据库插入失败", ServiceCode.INSERT_ERROR);
            }
        }else {
            Integer num = cart.getNum();
            cart.setNum(num+1);
            cartMapper.update(cart);
        }


    }

    @Override
    public PageR show(CartPageQueryDTO cartPageQueryDTO,TokenUser tokenUser) {
        PageHelper.startPage(cartPageQueryDTO.getPage(),cartPageQueryDTO.getPageSize());

        cartPageQueryDTO.setUserId(tokenUser.getId());
        cartPageQueryDTO.setUsername(tokenUser.getUsername());

        Page<CartVO> page=cartMapper.show(cartPageQueryDTO);

        return new PageR(page.getTotal(), page.getResult());
    }

    @Override
    public void subCart(Integer productId, TokenUser tokenUser) {
        Integer userId=tokenUser.getId();
        Cart cart=cartMapper.getByUserIdAndProductId(userId,productId);
        if(cart==null){
            throw new ServiceException("购物车中不存在该商品",ServiceCode.REQUEST_ERROR);
        }

        int num=cart.getNum();
        try {
            if(num>1){
                cart.setNum(num-1);
                cartMapper.update(cart);
            }else{
                cartMapper.delete(cart);
            }
        } catch (Exception e) {
            throw new ServiceException("数据库异常",ServiceCode.DATA_UPDATE_ERROR);
        }
    }
}
